//
//  CommentCell.m
//  MoneyApp
//
//  Created by leiyifan on 2017/2/20.
//  Copyright © 2017年 leiyifan. All rights reserved.
//

#import "CommentCell.h"
#import "CommentLab.h"
#import "UIImageView+WebCache.h"//图片加载

@interface CommentCell ()
@property (nonatomic,weak) UIImageView *headImage;
@property (nonatomic,weak) UILabel *nickName;
@property (nonatomic,weak) UILabel *timeLab;

@property (nonatomic,weak) UILabel *comment;

@property (nonatomic,weak) UIImageView *pageLine;

@property (nonatomic,weak) UITextView *answerView;

@end


@implementation CommentCell

+ (instancetype)commentCellWithTableView:(UITableView *)tableView andIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseId = @"CommentCell";
    CommentCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
    if (!cell) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId andIndexPath:indexPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}
// 重写构造方法，初始化（创建自定义cell内部的子控件）
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier andIndexPath:(NSIndexPath *)indexPath
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        //头像
        UIImageView *headImage = [UIImageView new];
        [self.contentView addSubview:headImage];
        headImage.layer.cornerRadius = 18;
        headImage.layer.masksToBounds = YES;
        headImage.clipsToBounds = YES;//不显示超出画布的图片
        headImage.contentMode = UIViewContentModeScaleAspectFill;
        headImage.backgroundColor = [UIColor redColor];
        self.headImage = headImage;
        
        //昵称
        UILabel *nickName = [UILabel new];
        [self.contentView addSubview:nickName];
        nickName.textColor = [UIColor blackColor];
        nickName.font = [UIFont systemFontOfSize:14];
        self.nickName = nickName;
        
        //时间
        UILabel *timeLab = [UILabel new];
        [self.contentView addSubview:timeLab];
        timeLab.textColor = [UIColor colorWithHexString:@"#aaaaaa"];
        timeLab.font = [UIFont systemFontOfSize:12];
        
        self.timeLab = timeLab;
        
        //点赞
        UIButton *zanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.contentView addSubview:zanBtn];
        zanBtn.hidden = YES;
        [zanBtn setTitleColor:[UIColor colorWithHexString:@"#aaaaaa"] forState:UIControlStateNormal];
        zanBtn.layer.borderWidth = 0.5;
        zanBtn.layer.borderColor = [UIColor colorWithHexString:@"#aaaaaa"].CGColor;
        zanBtn.layer.cornerRadius = 5;
        [zanBtn setTitle:@"详情" forState:UIControlStateNormal];
        zanBtn.layer.masksToBounds = YES;
        zanBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        
        self.zanBtn = zanBtn;
        
        //评论内容
        UILabel *comment = [UILabel new];
        [self.contentView addSubview:comment];
        comment.textColor = [UIColor colorWithHexString:@"#414145"];
        comment.font = [UIFont systemFontOfSize:14];
        comment.numberOfLines = 0;
        self.comment = comment;
        //虚线
        UIImageView *pageLine = [UIImageView new];
        [self.contentView addSubview:pageLine];
        pageLine.image = [UIImage imageNamed:@"dashLine"];
        self.pageLine = pageLine;
        
        //回复
        UITextView *answerView = [[UITextView alloc]init];
//        answerView.textInsets      = UIEdgeInsetsMake(0.f, 8.f, 0.f, 8.f);
        [self.contentView addSubview:answerView];
        answerView.backgroundColor = [UIColor colorWithHexString:@"#f8f8f8"];
//        answerView.font = KFont(12);
//        answerView.numberOfLines = 0;
        answerView.editable = NO;
        answerView.userInteractionEnabled = NO;
        answerView.layer.cornerRadius = 8;
        answerView.layer.masksToBounds = YES;
        answerView.layer.borderColor =[UIColor colorWithHexString:@"#f8f8f8"].CGColor;
        answerView.layer.borderWidth = 0.5;
//        answerView.textInsets = UIEdgeInsetsMake(5,5,0,0);
        
       
        self.answerView = answerView;
        
    }
    return self;
}

-(void)setLabelSpace:(UITextView*)label withValue:(NSString*)str withFont:(UIFont*)font {
    
   
    NSRange range;
    range = [str rangeOfString:@":"];
//    if (range.location != NSNotFound) {
//        NSLog(@"found at location = %lu, length = %lu",(unsigned long)range.location,(unsigned long)range.length);
//        NSString *ok = [str substringFromIndex:range.location];
//        NSLog(@"%@",ok);
//    }else{
//        NSLog(@"Not Found");
//    }
//    
   
    
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    
    
    
    
    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
    
    paraStyle.alignment = NSTextAlignmentJustified;
    paraStyle.lineSpacing = 5; //设置行间距
//    paraStyle.hyphenationFactor = 1.0;
//    paraStyle.firstLineHeadIndent = 8.0;
    paraStyle.paragraphSpacingBefore = 0.0;
    paraStyle.allowsDefaultTighteningForTruncation = YES;
    paraStyle.headIndent = 0;
    paraStyle.tailIndent = 0;
    //设置字间距 NSKernAttributeName:@1.5f
    NSDictionary *dic = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paraStyle, NSKernAttributeName:@0.f
                          ,NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#aaaaaa"]};
    
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:str attributes:dic];
  
    attributeStr =[self emojiText:str];
    
    [attributeStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,range.location+1)];
  
     label.attributedText = attributeStr;
   
//    label.attributedText = emojStr1;
}

-(void)setCommentFrame:(CommentFrame *)commentFrame{
    _commentFrame = commentFrame;
    //给子控件赋值
    [self setSubViewsContent];
    //设置Frame
    [self setSubViewsFrame];
}
-(void)setSubViewsContent{
    self.nickName.text = self.commentFrame.commentModel.postNickName;
    self.timeLab.text = self.commentFrame.commentModel.addtime;
    self.comment.text = self.commentFrame.commentModel.txt1;
//    NSMutableAttributedString *emojStr =[self emojiText:self.commentFrame.commentModel.txt1];
//     self.comment.attributedText = [[NSAttributedString alloc]initWithAttributedString:emojStr];
//    self.answerView.text = self.commentFrame.commentModel.comment;
    
    
    NSString *image1 = self.commentFrame.commentModel.postTxImg;
    NSURL *ImagePath1 =[NSURL URLWithString: image1];
    [self.headImage sd_setImageWithURL:ImagePath1 placeholderImage:[UIImage imageNamed:@"default"]];
    NSString *likeCount = [NSString stringWithFormat:@"%@ 赞",self.commentFrame.commentModel.dz];
//    [self.zanBtn setTitle:likeCount forState:UIControlStateNormal];
    
    //判断是否显示回复
    if (self.commentFrame.commentModel.comm.count == 0)  {
        self.answerView.hidden = YES;
        self.zanBtn.hidden = YES;
    }else{
        self.zanBtn.hidden = NO;
        self.answerView.hidden = NO;
        NSArray *array = self.commentFrame.commentModel.comm;
         NSDictionary *dict =array.firstObject;
        NSString *reText = [NSString stringWithFormat:@"%@ : %@",dict[@"uname"],dict[@"comment"]];
//        NSMutableAttributedString *emojStr1 =[self emojiText:reText];
//        self.answerView.attributedText = [[NSAttributedString alloc]initWithAttributedString:emojStr1];
        
        [self setLabelSpace: self.answerView withValue:reText withFont:[UIFont systemFontOfSize:14]];

    }
}
- (void)setSubViewsFrame
{
    self.headImage.frame = self.commentFrame.headImageFrame;
    self.nickName.frame = self.commentFrame.nickNameFrame;
    self.timeLab.frame = self.commentFrame.timeFrame;
    self.zanBtn.frame = self.commentFrame.zanCountFrame;
    self.comment.frame = self.commentFrame.commentFrame;
    self.pageLine.frame = self.commentFrame.pageLineFrame;
    self.answerView.frame = self.commentFrame.answerViewFrame;
}

//把文本换成表情
-(NSMutableAttributedString*) emojiText:(NSString*)str{
    if(!str){
        return nil;
    }
    if([str length]==0){
        return nil;
    }
    
    NSString *originalString=str;//文本信息
    NSMutableAttributedString * string = [[ NSMutableAttributedString alloc] initWithString:originalString  attributes:nil];//富文本信息
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[[a-zA-Z0-9\u4e00-\u9fa5]{1,}\\]" options:NSRegularExpressionAllowCommentsAndWhitespace error:&error];//正则替换
    //替换后返回一组数据
    NSArray *results = [regex matchesInString:originalString options:NSMatchingReportCompletion range:NSMakeRange(0, originalString.length)];
    //有内容的
    if (results) {
        for (NSTextCheckingResult *result in results.reverseObjectEnumerator) {
            NSRange resultRange = [result rangeAtIndex:0];//位置信息
            
            NSString *stringResult = [originalString substringWithRange:resultRange];//［中的字］
            //            stringResult = [NSString stringWithFormat:@"%ld",[stringResult integerValue]+1 ];
            if(stringResult!=nil){
                NSMutableString *mstr= [NSMutableString stringWithString:stringResult];
                
                //                NSCharacterSet*set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$?^?'@#$%^&*()_+'\""];
                //                NSString*trimmedString = [mstr stringByTrimmingCharactersInSet:set];
                //                trimmedString = [NSString stringWithFormat:@"%ld",[trimmedString integerValue]+1 ];
                //                if ([trimmedString integerValue] < 10) {
                //                    trimmedString = [NSString stringWithFormat:@"Emotion.bundle/00%@",trimmedString];
                //                }else if ([trimmedString integerValue] < 100 &&[trimmedString integerValue] >= 10){
                //                    trimmedString = [NSString stringWithFormat:@"Emotion.bundle/0%@",trimmedString];
                //                }else{
                //                    trimmedString = [NSString stringWithFormat:@"Emotion.bundle/%@",trimmedString];
                //                }
                //                [mstr replaceOccurrencesOfString:@"["
                //                                      withString:@""
                //                                         options:NSCaseInsensitiveSearch
                //                                           range:NSMakeRange(0,[mstr length])];
                //                [mstr replaceOccurrencesOfString:@"]"
                //                                      withString:@""
                //                                         options:NSCaseInsensitiveSearch
                //                                           range:NSMakeRange(0,[mstr length])];
                //
                /*
                 options 参数
                 NSCaseInsensitiveSearch = 1,//不区分大小写比较
                 
                 NSLiteralSearch = 2,//区分大小写比较
                 
                 NSBackwardsSearch = 4,//从字符串末尾开始搜索
                 
                 NSAnchoredSearch = 8,//搜索限制范围的字符串
                 
                 NSNumbericSearch = 64//按照字符串里的数字为依据，算出顺序。例如
                 */
                
                //  NSLog(@"%s %@\n", __FUNCTION__, mstr);//__FUNCTION__是当前方法名称宏
                NSString*trimmedString = [NSString stringWithFormat:@"Emotion.bundle/%@",mstr];
                NSTextAttachment * textAttachment = [[ NSTextAttachment alloc ] initWithData:nil ofType:nil ] ;
                NSLog(@"%@",mstr);
                UIImage * smileImage = [ UIImage imageNamed:trimmedString];  //my emoticon image named a.jpg
                
                textAttachment.image = smileImage ;
                textAttachment.bounds=CGRectMake(0, -5, 20, 20);
                NSAttributedString * textAttachmentString = [ NSAttributedString attributedStringWithAttachment:textAttachment ] ;
                [string replaceCharactersInRange:resultRange  withAttributedString:textAttachmentString] ;
            }
            
            
        }
        
    }
    return string ;
}
@end
